
package com.borqs.music.tasks;

import static com.borqs.music.util.MusicConf.ReqType.API_QUERY_VERSION;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.http.HttpRequest;
import com.borqs.music.http.HttpResponse;
import com.borqs.music.http.RequestMethod;
import com.borqs.music.model.VersionInfo;
import com.borqs.music.util.MusicConf;

/**
 * Task to get the latest version code of BorqsMusic on QiuPu
 * 
 * @author b554
 */
public class QueryVersionInfoTask extends Task {
    private static final String KEY_TYPE = "apps";
    private static final String KEY_ALL = "all";
    private String mTicket;

    public QueryVersionInfoTask(TaskListener listener, String ticket) {
        super(listener);
        mTicket = ticket;
    }

    @Override
    public HttpRequest prepareRequest() {
        Map<String, String> params = new HashMap<String, String>();
        params.put(KEY_TYPE, "com.borqs.music");
        params.put(KEY_ALL, "1");

        final String URL_QUERY_VERSION = MusicConf.getUrl(API_QUERY_VERSION);
        HttpRequest request = new HttpRequest(RequestMethod.GET, URL_QUERY_VERSION, mTicket, params);
        return request;
    }

    @Override
    public Object handleResponse(HttpResponse resp) throws Exception {
        checkResponse(resp);
        JSONArray array = resp.asJSONArray();
        JSONObject object = array.getJSONObject(0);      
        VersionInfo version = new VersionInfo(object.getString(JSON_VERSION_NAME),
                object.getInt(JSON_VERSION_CODE), object.getString(JSON_FILE_URL),
                object.getLong(JSON_FILE_SIZE));
        return version;
    }

    private static final String JSON_VERSION_NAME = "version_name";
    private static final String JSON_VERSION_CODE = "version_code";
    private static final String JSON_FILE_URL = "file_url";
    private static final String JSON_FILE_SIZE = "file_size";
}
